﻿using System;
using RestSharp;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Newtonsoft.Json;

namespace ContractDemo
{
    public class Program
    {
        private static readonly string RequestUrl = LetSignConfiguration.SandBoxRequestUrl;
        private static readonly DateTime TimeStampStartTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        public static JsonSerializerSettings JsonSetting = new JsonSerializerSettings()
        {
            NullValueHandling = NullValueHandling.Ignore
        };

        static void Main(string[] args)
        {
            // 获取企业章签的申请记录 - 已弃用
            // GetRequestDemo();

            // 获取个人认证链接
            // GetPersonCertUrl(); 

            // 获取企业认证链接
            // GetEnterpriseCertUrl();

            // 在线填充模板
            // PostFileRequestOnline(); -该场景不适用与出头的业务，使用下面Adobe模板的方式

            // 上传Adobe模板
            // PostFileRequestTemplate();

            // 申请企业自定义印章
            // ApplyCustomSignature();

            // 使用模板创建合同
            // PostCreateContractByAdobeTemplate();

            // 甲方  自动签署
            // AutoSign();

            // 查询签署状态
            // ContractStatus();

            // 乙方  申请签署链接
            // ApplyForSign();

            // 甲方   发起合同归档
            // ContractArchive();
        }

        /// <summary>
        /// 请求在线填充模板
        /// </summary>
        private static void PostFileRequestOnline()
        {
            string path = "/open-api/contract/file/template/createEditOnlineUrl";
            string url = RequestUrl + path;

            Dictionary<string, string> paramDict = new Dictionary<string, string>
            {
                {"templateName", "B2B协议合同"},
            };

            SecretHelper.AddAuthParam(paramDict, path);

            string filePath = "D:\\adobedc\\B2B协议合同.pdf";
            FileStream fs = File.OpenRead(filePath);
            Dictionary<string, FileStream> fileDict = new Dictionary<string, FileStream>
            {
                {"templateFile", fs}
            };

            HttpHelper.HttpRequest(url, paramDict, fileDict);
        }

        /// <summary>
        /// 上传adobe模板
        /// </summary>
        private static void PostFileRequestTemplate()
        {
            string path = "/open-api/contract/opt/uploadTemplate";
            string url = RequestUrl + path;

            Dictionary<string, string> paramDict = new Dictionary<string, string>
            {
                {"templateName", "出头B2B协议合同"},
            };

            SecretHelper.AddAuthParam(paramDict, path);

            string filePath = "D:\\adobedc\\出头B2B协议合同.pdf";
            FileStream fs = File.OpenRead(filePath);
            Dictionary<string, FileStream> fileDict = new Dictionary<string, FileStream>
            {
                {"templateFile", fs}
            };

            HttpHelper.HttpRequest(url, paramDict, fileDict);
        }

        /// <summary>
        /// 申请企业自定义印章
        /// </summary>
        private static void ApplyCustomSignature()
        {
            string path = "/open-api/signature/applyCustomSignature";
            string url = RequestUrl + path;

            Dictionary<string, string> paramDict = new Dictionary<string, string>
            {
                {"signatureName", "湖南某某机构自定义签章-V2"},
                {"companyOpenCode", "textHnMmJg"},
                {"callBackUrl", "http://47.96.19.47:10060/api/OpenContractApi/BtbContractNoticeForEvent"},
            };

            SecretHelper.AddAuthParam(paramDict, path);

            string filePath = "D:\\adobedc\\湖南某机构自定义章签.png";
            FileStream fs = File.OpenRead(filePath);
            Dictionary<string, FileStream> fileDict = new Dictionary<string, FileStream>
            {
                {"customSignaturePic", fs}
            };

            HttpHelper.HttpRequest(url, paramDict, fileDict);
        }

        /// <summary>
        /// 使用模板创建合同
        /// </summary>
        private static void PostCreateContractByAdobeTemplate()
        {
            string path = "/open-api/contract/opt/generate";
            string url = RequestUrl + path;

            // 组装参数
            var contractParams = new BtbContract
            {
                contract_index = "CT-8888666",
                contract_context = "湖南某机构与某企业A补充协议，测试文本！@#%&……***-+·123456789abcdefg",
                contract_partya = "湖南某机构",
                contract_partyb = "某企业A",
                contract_partya_date = DateTime.Now.ToString("yyyy-mm-dd"),
                contract_partyb_date = DateTime.Now.ToString("yyyy-mm-dd"),
                //contract_partya_year = "2022",
                //contract_partya_month = "6",
                //contract_partya_day = "21",
                //contract_partyb_year = "2024",
                //contract_partyb_month = "7",
                //contract_partyb_day = "31"
            };

            var paramsJson = JsonConvert.SerializeObject(contractParams, Formatting.Indented, JsonSetting);

            Dictionary<string, string> paramDict = new Dictionary<string, string>
            {
                //{"personOpenCode","zytTest17763771011"},
                // {"personOpenCode","gjmTest15575979776"},
                // {"personOpenCode","yjTest18670066245"},
                {"personOpenCode","Test15575979776"},
                {"companyOpenCode","textHnMmJg"},
                //{"companyOpenCode","textHnMmJg"},
               // {"companyOpenCode","textAAA"},
                {"params",paramsJson},
                {"signType","2"},
                //{"contractTemplateCode","06a4557c1af94e939079c6fbfe5af34e"}, // B2B协议合同
                {"contractTemplateCode","ad1bc22c587743c5914c919ffdd9200f"}, // 出头B2B协议合同 6页 
            };

            SecretHelper.AddAuthParam(paramDict, path);

            HttpHelper.HttpRequest(url, paramDict, Method.POST);
        }

        /// <summary>
        /// 个人认证链接
        /// </summary>
        private static void GetPersonCertUrl()
        {
            string path = "/open-api/certification/getCertUrl";
            string url = RequestUrl + path;

            Dictionary<string, string> paramDict = new Dictionary<string, string>
            {
                //{"personOpenCode","Test15575979776"},
                //{"personOpenCode","gjmTest15575979776"},
                //{"personOpenCode","yjTest18670066245"},
                //{"personOpenCode","zytTest17763771011"},
               // {"personOpenCode","abc222222"},
                {"personOpenCode","abc222222"},
                {"needIdCardOcr","0"}, // 是否需要进行身份证OCR  1:是，0:否默认为1；
                // {"personIdCardType","117"},// 身份证
                // {"personIdCard","430423--------3632"}, // 身份证
                {"refAsyncNotifyUrl","http://47.96.19.47:10060/api/OpenContractApi/BtbContractNoticeForEvent"},
            };

            SecretHelper.AddAuthParam(paramDict, path);

            HttpHelper.HttpRequest(url, paramDict, Method.POST);
        }

        /// <summary>
        /// 获取企业认证链接
        /// </summary>
        private static void GetEnterpriseCertUrl()
        {
            string path = "/open-api/certification/getEntCertUrl";
            string url = RequestUrl + path;

            Dictionary<string, string> paramDict = new Dictionary<string, string>
            {
                //{"personOpenCode","Test15575979776"},
                //{"personOpenCode","gjmTest15575979776"},
                //{"personOpenCode","yjTest18670066245"},
               // {"companyOpenCode","textHnMmJg"},
               // {"personOpenCode","zytTest17763771011"},
                {"personOpenCode","abcTest15684958622"},
               // {"companyOpenCode","testCtkjYqn"},
                {"companyOpenCode","textHnMmJg"},
                {"refAsyncNotifyUrl","http://47.96.19.47:10060/api/OpenContractApi/BtbContractNoticeForEvent"},
            };

            SecretHelper.AddAuthParam(paramDict, path);

            HttpHelper.HttpRequest(url, paramDict, Method.POST);
        }

        /// <summary>
        /// 申请签署链接   - 乙方  
        /// </summary>
        private static void ApplyForSign()
        {
            string path = "/open-api/contract/sign/v2/applyForSign";
            string url = RequestUrl + path;


            #region 构造签署位置列表数据

            var signList = new List<SignCoordinate>()
            {
                new SignCoordinate
                {
                    PdfPage = "6",
                    Vertical = "1024",
                    Horizontal = "2048"
                }
            };
            var sBuild = new StringBuilder();
            foreach (var sign in signList)
            {
                sBuild.AppendFormat("&{0}", JsonConvert.SerializeObject(sign));
            }

            var signCoordinateJson = sBuild.Remove(0, 1).ToString();

            var signLocation = new List<SignLocationDto>()
            {
               new SignLocationDto()
               {
                   FileOrder = 1,
                   SealType = 1,
                   //LocateMode = 2,  //  1 关键字  2 坐标
                   //SignCoordinate = signCoordinateJson   //  如果为坐标，则必填
                   LocateMode = 1,
                   KeyWord = "某企业A",
                   ScanPage = "6",
               }
            };

            var signLocations = JsonConvert.SerializeObject(signLocation, Formatting.Indented, JsonSetting);
            #endregion


            Dictionary<string, string> paramDict = new Dictionary<string, string>
            {
                {"personOpenCode","zytTest17763771011"},   // 乙方个人code
               // {"personOpenCode","Test15575979776"},    //  甲方 个人code
                //{"personOpenCode","gjmTest15575979776"},
                //{"personOpenCode","yjTest18670066245"},
                {"companyOpenCode","textAAA"},    // 乙方企业 code
               // {"companyOpenCode","textHnMmJg"},   // 甲方企业 code
                //{"companyOpenCode","testCtkjYqn"},
                {"contractCode","7a36983b54924f2b8c1c27ce52dd6cc5"},// 湖南某某机构与企业A-出头B2B协议合同 关键字 某企业A
                //{"contractCode","9301427a04ad485db05930e235c187b7"},// 湖南某某机构与企业A-出头B2B协议合同  已签署 坐标
                // {"contractCode","e307cb4f1f8a483fbc218db68b97282b"},// 湖南某某机构与企业A-出头B2B协议合同  已签署
                {"signLocations",signLocations},
                //{"signLocations","[{\"locateMode\":2,\"signCoordinate\":[{\"pdfPage\":\"1\",\"vertical\":\"0\",\"horizontal\":\"0\"},{\"pdfPage\":\"1\",\"vertical\":\"0\",\"horizontal\":\"0\"}]}]"},
                {"signTypeLimits","10"},
                {"signValidMethod","3"},
                {"transactionCode","abcd123456789qwerabcd123456789ttt202"},// 签章事务编码	
                {"postSignCallback","http://47.96.19.47:10060/api/OpenContractApi/BtbContractNoticeForSign"},
            };

            SecretHelper.AddAuthParam(paramDict, path);

            HttpHelper.HttpRequest(url, paramDict, Method.POST);
        }

        /// <summary>
        /// 自动签署    -  甲方
        /// </summary>
        private static void AutoSign()
        {
            string path = "/open-api/contract/sign/v2/autoSign";
            string url = RequestUrl + path;

            #region 构造签署位置列表数据

            var signList = new List<SignCoordinate>()
            {
                //new SignCoordinate
                //{
                //    PdfPage = "5",
                //    Vertical = "1024",
                //    Horizontal = "2048"
                //},
                new SignCoordinate
                {
                    PdfPage = "6",
                    Vertical = "500",
                    Horizontal = "200"
                }
            };

            var sBuild = new StringBuilder();
            foreach (var sign in signList)
            {
                sBuild.AppendFormat("&{0}", JsonConvert.SerializeObject(sign));
            }

            var signCoordinateJson = sBuild.Remove(0, 1).ToString();
            var signLocation = new List<SignLocationDto>()
            {
               new SignLocationDto()
               {
                   FileOrder = 1,
                   SealType = 1,
                   LocateMode = 2,
                   SignCoordinate = signCoordinateJson
               }
            };

            var signLocations = JsonConvert.SerializeObject(signLocation, Formatting.None, JsonSetting);
            #endregion

            Dictionary<string, string> paramDict = new Dictionary<string, string>
            {
               // {"personOpenCode","zytTest17763771011"},
                {"personOpenCode","Test15575979776"},
                //{"personOpenCode","gjmTest15575979776"},
                //{"personOpenCode","yjTest18670066245"},
                //{"companyOpenCode","textAAA"},
                {"companyOpenCode","textHnMmJg"},
                //{"companyOpenCode","testCtkjYqn"},
                {"contractCode","7a36983b54924f2b8c1c27ce52dd6cc5"},// 湖南某某机构与企业A 
                //{"contractCode","9301427a04ad485db05930e235c187b7"},// 湖南某某机构与企业A 已签署
                //{"contractCode","e307cb4f1f8a483fbc218db68b97282b"},// 湖南某某机构与企业A 已签署
                //{"contractCode","a764d93faf734bc788e69668fe6507b0"},  // 出头与湖南某某机构
                //{"signLocations","[{\"FileOrder\":1,\"SealType\":1,\"LocateMode\":2,\"KeyWord\":null,\"ScanPage\":null,\"SignCoordinate\":[{\"PdfPage\":\"1\",\"Vertical\":\"1024\",\"Horizontal\":\"2048\"}],\"DateSealFormat\":0}]"},
                //{"signLocations",signLocations},
                //{"signLocations","[{\"fileOrder\":1,\"sealType\":1,\"locateMode\":2,\"signCoordinate\":\"{\\\"pdfPage\\\":\\\"1\\\",\\\"vertical\\\":\\\"668\\\",\\\"horizontal\\\":\\\"200\\\"}&{\\\"pdfPage\\\":\\\"1\\\",\\\"vertical\\\":\\\"657\\\",\\\"horizontal\\\":\\\"165\\\"}\"}]"},
                {"signLocations",signLocations},
                {"signTypeLimits","10"},
                {"signValidMethod","3"},
                {"signatureCode","7112622232257430308"},
                //{"transactionCode","abcd123456789qwerabcd123456789ttt101"},// 签章事务编码  已归档
                {"transactionCode","abcd123456789qwerabcd123456789ttt201"},// 签章事务编码
                {"postSignCallback","http://47.96.19.47:10060/api/OpenContractApi/BtbContractNoticeForSign"},
            };

            SecretHelper.AddAuthParam(paramDict, path);

            HttpHelper.HttpRequest(url, paramDict, Method.POST);
        }

        /// <summary>
        /// 合同归档
        /// </summary>
        private static void ContractArchive()
        {
            string path = "/open-api/contract/opt/archive";
            string url = RequestUrl + path;

            Dictionary<string, string> paramDict = new Dictionary<string, string>
            {
                {"personOpenCode","test15575979776"},
                {"companyOpenCode","textHnMmJg"},
                //{"contractCode","e307cb4f1f8a483fbc218db68b97282b"}, // 已归档
                //{"contractCode","9301427a04ad485db05930e235c187b7"},  // 已归档
            };

            SecretHelper.AddAuthParam(paramDict, path);

            HttpHelper.HttpRequest(url, paramDict, Method.POST);
        }

        /// <summary>
        /// 签署状态查询
        /// </summary>
        private static void ContractStatus()
        {
            string path = "/open-api/contract/sign/signStatus";
            string url = RequestUrl + path;

            Dictionary<string, string> paramDict = new Dictionary<string, string>
            {
                {"transactionCode","abcd123456789qwerabcd123456789ttt201"},
            };

            SecretHelper.AddAuthParam(paramDict, path);

            HttpHelper.HttpRequest(url, paramDict, Method.POST);
        }


        /// <summary>
        /// Post请求
        /// </summary>
        private static void PostRequestDemo()
        {
            string path = "/open-api/certification/getCertUrl";
            string url = RequestUrl + path;

            Dictionary<string, string> paramDict = new Dictionary<string, string>
            {
                {"personOpenCode","test15575979776"},
                {"companyOpenCode","textHnMmJg"},
                {"personOpenCode","e307cb4f1f8a483fbc218db68b97282b"},
            };

            SecretHelper.AddAuthParam(paramDict, path);

            HttpHelper.HttpRequest(url, paramDict, Method.POST);
        }

        /// <summary>
        /// Get请求
        /// </summary>
        private static void GetRequestDemo()
        {
            string path = "/open-api/signature/auth/query/{signatureApplicationCode}";
            string url = RequestUrl + path;

            Dictionary<string, string> paramDict = new Dictionary<string, string>
            {
                {"signatureApplicationCode", "7112622231057859359"},
            };

            SecretHelper.AddAuthParam(paramDict, path);

            HttpHelper.HttpRequest(url, paramDict, Method.GET);
        }
    }
}
